/** 
 * Project Name:kaka 
 * File Name:BasicInfoAction.java 
 * Package Name:com.luoran.kaka.action 
 * Date:2018年11月21日上午10:11:49 
 * Copyright (c) 2018, Luoran, Inc. All Rights Reserved.
 * 
 */
package com.luoran.kaka.action;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.luoran.kaka.entity.AboutInfo;
import com.luoran.kaka.entity.BasicInfo;
import com.luoran.kaka.entity.ExtraInfo;
import com.luoran.kaka.entity.PicInfo;
import com.luoran.kaka.service.IAboutInfoService;
import com.luoran.kaka.service.IBasicInfoService;
import com.luoran.kaka.service.IExtraInfoService;
import com.luoran.kaka.service.IPicInfoService;
import com.luoran.kaka.utils.UUID;

/** 
 * ClassName: BasicInfoAction
 * date: 2018年11月21日 上午10:11:49
 * @author ghl 
 * @since JDK 1.8
 */
@Controller
@RequestMapping("/basic")
public class BasicInfoAction {

	private static final Logger log = LoggerFactory.getLogger(BasicInfoAction.class);

	@Autowired
	private IBasicInfoService basicInfoService;

	@Autowired
	private IPicInfoService picInfoService;

	@Autowired
	private IExtraInfoService extraInfoService;

	@Autowired
	private IAboutInfoService aboutInfoService;

	@Autowired
	private Environment evn;

	/**
	 * personalCard:(跳转到简易卡片).
	 * @author ghl
	 * @return 
	 * @since JDK 1.8
	 */
	@RequestMapping("/simple/{openId}")
	public String simpleCard(@PathVariable("openId")String openId,Model model) {
		log.info("跳转到新增个人简易卡片,参数openId为{{}}",openId);
		model.addAttribute("openId", openId);
		return "personal/personal-simple";
	}


	/**
	 * 
	 * @author ghl 2018年11月22日下午4:26:47
	 * @param req
	 * @return 
	 * @since JDK 1.8
	 * upload:文件上传
	 */
	@RequestMapping("/simple/upload")
	@ResponseBody
	public JSONObject upload(HttpServletRequest req) {
		log.info(" 开始上传图片");
		JSONObject obj = new JSONObject();
		PicInfo pic = new PicInfo();
		String data = (String) req.getParameter("base64");// 接收前台的base64图片数据
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
			Iterator<String> fileNames = multipartRequest.getFileNames();
			MultipartFile file = multipartRequest.getFile(fileNames.next());
			String originalName = file.getOriginalFilename();// 源文件名称
			String suffix = originalName.substring(originalName.lastIndexOf(".")).toLowerCase();// 原始后缀小写
			long size = file.getSize();// 源文件大小
			String path = evn.getProperty("file.path");// 获取图片存储目录
			String newFileName = UUID.get() + suffix;// 根据UUID生成新的文件名称带后缀
			String depositUrl = path + "/" + newFileName;
			File dest = new File(depositUrl);// 上传目标路径

			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
				log.info("父及目录不存在，创建父及目录。");
			}
			file.transferTo(dest);// 图片上传
			pic.setOriginalName(originalName);
			pic.setSize((int) size);
			pic.setName(newFileName);
			pic.setDepositUrl(depositUrl);
			pic.setUrl(evn.getProperty("file.path.url") + req.getContextPath() + "/" + newFileName);// 根据配置的虚拟路径可以直接用url访问本地图片,正式上线可以通过nginx反向代理访问linux图片目录
			pic.setCreatetime(new Date());
			pic.setLastupdatetime(new Date());
			String picId = picInfoService.insertPic(pic);
			if (null != picId) {
				log.info("图片上传成功");
				obj.put("picId", picId);
				obj.put("src", data);
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return obj;
	}


	/**
	 *
	 * @author ghl 2018年11月22日下午6:26:04
	 * @param info
	 * @return 
	 * @since JDK 1.8
	 * simpleAddUser: 点击完成/继续按钮
	 */
	@RequestMapping("/simple/save")
	@ResponseBody
	public JSONObject simpleAddUser(BasicInfo info) {
		JSONObject obj = new JSONObject();
		
		if (StringUtils.isEmpty(info.getUserName())) {
			obj.put("flag", false);
			obj.put("msg", "请输入用户名");
			return obj;
		} else if (StringUtils.isEmpty(info.getWxOpenId())) {
			//未获取到openId
			obj.put("flag", false);
			obj.put("msg", "网络异常,请刷新重试");
			return obj;
		} else{
			info.setCreatetime(new Date());
			String userId = basicInfoService.add(info);
			if (StringUtils.isEmpty(userId)) {
				obj.put("flag", false);
				obj.put("msg", "网络开小差了:(");
				return obj;
			} else {
				obj.put("flag", true);
				obj.put("msg", "成功");
				obj.put("userId", userId);
				return obj;
			}
		}
	}


	/** 
	 * 
	 * @author ghl 2018年11月26日上午12:35:14
	 * @param id
	 * @param model
	 * @return 
	 * @since JDK 1.8
	 * moreCardInfo:跳转更多卡片信息
	 */
	@RequestMapping("/card/{id}")
	public String moreCardInfo(@PathVariable("id") String id, Model model) {
		if (!StringUtils.isEmpty(id)) {
			log.info("userId =====> {}", id);
			try {
				BasicInfo basicInfo = basicInfoService.getBasicInfoById(id);
				if (null != basicInfo) {
					model.addAttribute("info", basicInfo);
					log.info("获取basicInfo成功");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		log.info(" ==== > 跳转到个人卡片");
		return "personal/personal-card";
	}


	/** 
	 * 
	 * @author ghl 2018年11月26日上午12:09:09
	 * @param basicInfo
	 * @return 
	 * @since JDK 1.8
	 * addMore:添加更多信息
	 */
	@RequestMapping("/card/addMore")
	@ResponseBody
	public JSONObject addMore(BasicInfo basicInfo, HttpServletRequest req) {
		JSONObject obj = new JSONObject();
		String extraInfo = req.getParameter("extraInfo");// 如果前台传来的有额外信息
		if (!StringUtils.isEmpty(extraInfo) && !"{}".equals(extraInfo)) {
			String id = extraInfoService.addExtraInfo(extraInfo);
			if (!StringUtils.isEmpty(id)) {
				log.info("额外信息添加成功");
				basicInfo.setExtraInfoId(id);
			}
		}
		int count;
		try {
			count = basicInfoService.updateUserInfo(basicInfo);
		} catch (Exception e) {
			log.error(e.getMessage());
			obj.put("flag", false);
			obj.put("msg", "失败");
			return obj;
		}
		if (count == 1) {
			log.info("基本信息更新成功");
			obj.put("flag", true);
			obj.put("msg", "更新成功");
			obj.put("userId", basicInfo.getId());
			return obj;
		} else {
			obj.put("flag", false);
			obj.put("msg", "失败");
			return obj;
		}
	}


	/** 
	 * 
	 * @author ghl 2018年11月25日下午11:49:20
	 * @param userId
	 * @param model
	 * @return 
	 * @since JDK 1.8
	 * my:
	 */
	@RequestMapping("/my/{id}")
	public String my(@PathVariable("id") String id, Model model) {
		log.info("跳转到我的名片展示");
		log.info("获取名片卡片信息,参数名片id为{{}}",id);
		BasicInfo basicInfo = basicInfoService.getBasicInfoById(id);
		if (null != basicInfo) {
			log.info("获取名片头像信息,参数图片id为{{}}",basicInfo.getPicId());
			PicInfo pic = picInfoService.getPicInfoById(basicInfo.getPicId());
			if (null != pic) {
				model.addAttribute("picUrl", pic.getUrl());
				log.info("个人头像获取成功,URL为{{}}", pic.getUrl());
			}
		}
		model.addAttribute("info", basicInfo);
		return "personal/personal-my";
	}


	@RequestMapping("/my/detail/{id}")
	public String myDetailInfo(@PathVariable("id") String id, Model model) {
		log.info("开始获取我的详细信息");
		BasicInfo basicInfo = basicInfoService.getBasicInfoById(id);
		if (null != basicInfo) {
			PicInfo pic = picInfoService.getPicInfoById(basicInfo.getPicId());
			if (null != pic) {
				model.addAttribute("picUrl", pic.getUrl());
				log.info("个人图片获取成功,访问URL为: {}", pic.getUrl());
			}
		}
		model.addAttribute("info", basicInfo);
		return "personal/personal-detail";
	}

	/** 
	 * 
	 * @author ghl 2018年11月29日下午6:08:38
	 * @param id
	 * @return 
	 * @since JDK 1.8
	 * getExtraInfo:获取额外信息
	 */
	@RequestMapping("/my/extra/{id}")
	@ResponseBody
	public JSONObject getExtraInfo(@PathVariable("id") String id) {
		JSONObject obj = new JSONObject();
		log.info("获取额外信息");
		ExtraInfo extra = extraInfoService.getExtraInfoByUserId(id);
		if (null != extra) {
			String extraInfo = extra.getExtraInfo();
			if (!StringUtils.isEmpty(extraInfo)) {
				try {
					JSONObject object = JSON.parseObject(extraInfo);
					obj.put("info", object);
					obj.put("flag", true);
					return obj;
				} catch (Exception e) {
					e.printStackTrace();
					obj.put("info", "数据解析失败");
					obj.put("flag", false);
					return obj;
				}
			} else {
				obj.put("info", "暂无数据");
				obj.put("flag", false);
				return obj;
			}
		} else {
			obj.put("info", "暂无数据");
			obj.put("flag", false);
			return obj;
		}
	}

	
	@RequestMapping("/detail/about/add/{id}")
	public String addMyAboutInfo(@PathVariable("id")String id , Model model) {
		log.info(" ==== > 跳转到个人卡片-添加个人风采");
		model.addAttribute("basicInfoId", id);
		return "personal/personal-about";
	}

	/** 
	 * 
	 * @author ghl 2018年12月4日下午2:28:36
	 * @param id
	 * @return 
	 * @since JDK 1.8
	 * getAboutInfo:获取个人风采
	 */
	@RequestMapping("/detail/about/view/{id}")
	@ResponseBody
	public JSONObject getAboutInfo(@PathVariable("id") String id) {
		log.info("获取个人风采,参数ID为:{}", id);
		JSONObject obj = new JSONObject();
		try {
			List<Object> list = aboutInfoService.getAboutInfosById(id);
			if (list != null && list.size()>0) {
				obj.put("flag", true);
				obj.put("list", list);
				return obj;
			} else {
				obj.put("flag", false);
				obj.put("msg", "暂无个人风采");
				return obj;
			}
		} catch (Exception e) {
			e.printStackTrace();
			obj.put("flag", false);
			obj.put("msg", "网络异常");
			return obj;
		}
	}

	/** 
	 * 
	 * @author ghl 2018年12月3日下午2:04:20
	 * @param req
	 * @return 
	 * @since JDK 1.8
	 * multiUpload:个人风采图片保存
	 */
	@RequestMapping("/detail/multiUpload")
	@ResponseBody
	public JSONObject multiUpload(HttpServletRequest req) {
		log.info("上传个人风采图片");
		JSONObject obj = new JSONObject();
		PicInfo pic = new PicInfo();
		String data = req.getParameter("base64");
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
			Iterator<String> fileNames = multipartRequest.getFileNames();
			MultipartFile file = multipartRequest.getFile(fileNames.next());
			String originalName = file.getOriginalFilename();// 源文件名称
			String suffix = originalName.substring(originalName.lastIndexOf(".")).toLowerCase();// 原始后缀小写
			long size = file.getSize();// 源文件大小
			String path = evn.getProperty("file.path");// 获取图片存储目录
			String newFileName = UUID.get() + suffix;// 根据UUID生成新的文件名称带后缀
			String depositUrl = path + "/" + newFileName;
			File dest = new File(depositUrl);// 上传目标路径

			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
				log.info("父及目录不存在，创建父及目录。");
			}
			file.transferTo(dest);// 图片上传
			pic.setOriginalName(originalName);
			pic.setSize((int) size);
			pic.setName(newFileName);
			pic.setDepositUrl(depositUrl);
			pic.setUrl(evn.getProperty("file.path.url") + req.getContextPath() + "/" + newFileName);// 根据配置的虚拟路径可以直接用url访问本地图片,正式上线可以通过nginx反向代理访问linux图片目录
			pic.setCreatetime(new Date());
			pic.setLastupdatetime(new Date());
			String picId = picInfoService.insertPic(pic);
			if (null != picId) {
				log.info("图片上传成功");
				obj.put("picId", picId);
				obj.put("src", data);
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return obj;
	}


	/** 
	 * 
	 * @author ghl 2018年12月3日下午4:22:08
	 * @param aboutInfo
	 * @return 
	 * @since JDK 1.8
	 * saveMyAbout:
	 */
	@RequestMapping("/detail/about/save")
	@ResponseBody
	public JSONObject saveMyAbout(AboutInfo aboutInfo) {
		JSONObject obj = new JSONObject();
		if (StringUtils.isEmpty(aboutInfo.getTextContext())) {
			obj.put("flag", false);
			obj.put("msg", "文字描述不能为空");
			return obj;
		}
		if (StringUtils.isEmpty(aboutInfo.getBasicInfoId())) {
			obj.put("flag", false);
			obj.put("msg", "网络异常");
			return obj;
		}
		aboutInfo.setCreatetime(new Date());
		aboutInfo.setLastupdatetime(new Date());
		try {
			String id = aboutInfoService.saveAboutInfo(aboutInfo);
			if (!StringUtils.isEmpty(id)) {
				obj.put("flag", true);
				obj.put("msg", "保存成功");
				obj.put("id", aboutInfo.getBasicInfoId());
				return obj;
			} else {
				obj.put("flag", false);
				obj.put("msg", "保存个人风采失败");
				return obj;
			}
		} catch (Exception e) {
			e.printStackTrace();
			obj.put("flag", false);
			obj.put("msg", "保存个人风采失败");
			return obj;
		}
	}


	@RequestMapping("/my/update/{id}")
	@ResponseBody
	public JSONObject updateBasicInfo(@PathVariable("id") String id, String aboutId) {
		JSONObject obj = new JSONObject();
		if (StringUtils.isEmpty("id")) {
			obj.put("msg", "参数获取异常");
			obj.put("flag", false);
			return obj;
		} else {
			BasicInfo basicInfo = new BasicInfo();
			basicInfo.setId(id);
			try {
				basicInfoService.updateUserInfo(basicInfo);
				obj.put("msg", "更新成功");
				obj.put("flag", true);
				return obj;
			} catch (Exception e) {
				e.printStackTrace();
				obj.put("msg", "网络异常，更新失败");
				obj.put("flag", false);
				return obj;
			}
		}
	}

	/**
	 * 
	 * successPage:(操作成功返回到成功页面并携带消息).
	 * 
	 * @author ghl
	 * @param msg
	 * @param m
	 * @return 
	 * @since JDK 1.8
	 */
	@RequestMapping("/success")
	public String successPage(String msg, Model m) {
		m.addAttribute("msg", msg);
		return "common/success";
	}
}
